package com.kedacom.general.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.regex.Pattern;

public class FileUtils {

    public static MultipartFile base64ToMultipartFile (String base64) throws IOException  {

        String base64Pattern = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$";
        final String[] base64Array = base64.split(",");
        if (Pattern.matches(base64Pattern, base64Array[0])){
            String dataUir, data;
            if (base64Array.length > 1) {
                dataUir = base64Array[1];
                data = base64Array[0];
            } else {
                //根据你base64代表的具体文件构建
                dataUir = "jpg";
                data = base64Array[0];
            }
            return new Base64ToMultipartFile(data, dataUir);
        }else{
            return null;
        }
    }
    public  static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;

    }

    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {

        }
    }
}
